package com.example.springboot.common;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.example.springboot.entity.Admin;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.service.IAdminService;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class JwtInterceptor implements HandlerInterceptor {

    private static final String ERROR_CODE_401 = "401";

    @Autowired
    private IAdminService adminService;

    @Override
    public boolean preHandle(@NonNull HttpServletRequest request,
                             @NonNull HttpServletResponse response,
                             @NonNull Object handler) {
        //获取uri
        String requestURI = request.getRequestURI();
        //获取token
        String token = request.getHeader("token");

        // 如果你的请求是跨域的，浏览器会先发一个 OPTIONS 请求做预检。（@CrossOrigin跨域注解的原因）这个请求没有 Authorization 头，会被拦截器误判为“无 Token”。
        //解决方案：在拦截器中放行 OPTIONS 请求。
        // OPTIONS请求直接放行
//        if ("OPTIONS".equals(request.getMethod())) {
//            log.info("跨域OPTIONS 请求，放行");
//            return true;
//        }

        // 放行登录接口
        if (requestURI.contains("/login")) {
            return true;
        }

        if (StrUtil.isBlank(token)) {
            token = request.getParameter("token");
        }


        if (StrUtil.isBlank(token)) {
            throw new ServiceException(ERROR_CODE_401, "无token，请重新登录");
        }


        String adminId;
        Admin admin;
        try {
            adminId = JWT.decode(token).getAudience().get(0);

            admin = adminService.getById(Integer.parseInt(adminId));
        } catch (Exception e) {
            String errMsg = "token验证失败，请重新登录";
            log.error(errMsg + ", token=" + token, e);
            throw new ServiceException(ERROR_CODE_401, errMsg);
        }
        if (admin == null) {
            throw new ServiceException(ERROR_CODE_401, "用户不存在，请重新登录");
        }


        try {
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(admin.getPassword())).build();
            jwtVerifier.verify(token);
        } catch (JWTVerificationException e) {
            throw new ServiceException(ERROR_CODE_401, "token验证失败，请重新登录");
        }
        return true;
    }

}
